package com.example.onlinemarket.activity;


import android.content.Context;
import android.content.Intent;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;


import com.example.onlinemarket.Application;
import com.example.onlinemarket.R;
import com.example.onlinemarket.util.LogUtil;


import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


import static com.example.onlinemarket.Application.dismissProgressDialog;
import static com.example.onlinemarket.Application.showProgressDialog;
import static com.example.onlinemarket.util.HttpUtil.sendHttpRequest;

public class RegisterActivity extends BaseActivity {

    private EditText userNameEt;
    private EditText passwordEt;
    private EditText confirmPasswordEt;
    private EditText emailEt;
    private EditText addressEt;
    private TextView tip;
    private Button registerBtn;
    private boolean isInfoLegal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载资源
        loadResources();
    }

    //加载资源
    private void loadResources() {
        //设置布局
        setContentView(R.layout.activity_register);
        //初始化组件
        initWidgets();
        //加载Intent传递过来的数据
        loadIntentMsg();
        //为组件设置监听器
        setWidgetsListener();
        //关闭加载提示框
        dismissProgressDialog();
    }


    //加载Intent传递过来的数据
    private void loadIntentMsg() {
        Intent registerIntent = getIntent();
        userNameEt.setText(registerIntent.getStringExtra("userName"));
        passwordEt.setText(registerIntent.getStringExtra("password"));
        confirmPasswordEt.setText(registerIntent.getStringExtra("password"));
    }

    //初始化组件
    private void initWidgets() {
        userNameEt = findViewById(R.id.et_register_userName);
        passwordEt = findViewById(R.id.et_register_password);
        confirmPasswordEt = findViewById(R.id.et_register_passwordRepeated);
        emailEt = findViewById(R.id.et_register_email);
        addressEt = findViewById(R.id.et_register_address);
        tip = findViewById(R.id.tv_register_tip);
        registerBtn = findViewById(R.id.btn_register_register);
    }

    //为组件设置监听器
    private void setWidgetsListener(){
        registerBtn.setOnClickListener(v -> new Thread(this::register).start());
        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                String userName = userNameEt.getText().toString().trim();
                if(userName.isEmpty()) {
                    tip.setText("请输入用户名");
                    registerBtn.setEnabled(false);
                    isInfoLegal = false;
                }
                else{
                    String pwd = passwordEt.getText().toString().trim();
                    if(pwd.isEmpty()) {
                        tip.setText("请输入密码");
                        registerBtn.setEnabled(false);
                        isInfoLegal = false;
                    }
                    else{
                        String confirmPwd = confirmPasswordEt.getText().toString().trim();
                        if(confirmPwd.isEmpty()){
                            tip.setText("请再次确认密码");
                            registerBtn.setEnabled(false);
                            isInfoLegal = false;
                        }else if(!confirmPwd.equals(pwd)){
                            tip.setText("两次输入的密码不一致");
                            registerBtn.setEnabled(false);
                            isInfoLegal = false;
                        }else{
                            String email = emailEt.getText().toString().trim();
                            if(email.isEmpty()){
                                tip.setText("邮箱不能为空");
                                registerBtn.setEnabled(false);
                                isInfoLegal = false;
                            }else{
                                String address = addressEt.getText().toString().trim();
                                if(address.isEmpty()){
                                    tip.setText("地址不能为空");
                                    registerBtn.setEnabled(false);
                                    isInfoLegal = false;
                                }else {
                                    tip.setText("");
                                    registerBtn.setEnabled(true);
                                    isInfoLegal = true;
                                }
                            }
                        }
                    }
                }
            }
        };
        userNameEt.addTextChangedListener(watcher);
        passwordEt.addTextChangedListener(watcher);
        confirmPasswordEt.addTextChangedListener(watcher);
        emailEt.addTextChangedListener(watcher);
        addressEt.addTextChangedListener(watcher);
        addressEt.setOnEditorActionListener((v, actionId, event) -> {
            if(isInfoLegal
                    &&((actionId == EditorInfo.IME_ACTION_DONE)||(event.getKeyCode() == KeyEvent.KEYCODE_ENTER))){
                hideKeyboard();//隐藏软键盘
                registerBtn.callOnClick();
            }
            return true;
        });
    }

    //隐藏软键盘
    private void hideKeyboard() {
        addressEt.clearFocus();
        View decorView = getWindow().peekDecorView();
        if (decorView != null) {
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(decorView.getWindowToken(), 0);
        }
    }

    private void register() {
        new Thread(() -> {
            String userName = userNameEt.getText().toString().trim();
            //接下来应当检验用户名是否能够注册
            Map<String,String> map = new HashMap<>();
            map.put("userName", userName);
            //弹出加载进度条
            runOnUiThread(() -> showProgressDialog(this, "注册中，请稍候..."));
            if(Objects.equals(sendHttpRequest("/isUserExists", "POST", map), "true")) {
                //关闭加载进度条
                runOnUiThread(() -> {
                    registerBtn.setEnabled(false);
                    tip.setText("用户名已存在");
                    dismissProgressDialog();
                });
            }
            else{
                //清空错误提示信息
                runOnUiThread(() -> tip.setText(""));
                String pwd = passwordEt.getText().toString().trim();
                String email = emailEt.getText().toString().trim();
                String address = addressEt.getText().toString().trim();
                map.put("password", pwd);
                map.put("email", email);
                map.put("address", address);
                String responseData = sendHttpRequest("/register", "POST", map);
                if(responseData!=null&&!responseData.isEmpty()){
                    if(responseData.equals("\"1\"")){
                        Intent backIntent = new Intent();
                        backIntent.putExtra("userName", userName);
                        backIntent.putExtra("password", pwd);
                        //跳转回LoginActivity并销毁当前Activity
                        runOnUiThread(() -> {
                            dismissProgressDialog();
                            setResult(RESULT_OK, backIntent);
                            finish();
                        });
                    }
                }else runOnUiThread(() -> {
                    tip.setText("网络异常，请稍后再试");
                    tip.setVisibility(View.VISIBLE);
                });
            }
        }).start();
    }
}